<script lang="ts" setup>
	import {
		reactive,
		inject,
		ref,
		getCurrentInstance,
		watch,
		computed
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import user from '@/api/user.js'
	import chat from '@/api/chat.js'
	import article from '@/api/article.js'
	import tree from '@/components/tree_list.vue'
	import pageLoading from '@/components/pageLoading.vue'
	import emoji from '@/components/emoji.vue'
	import {
		useStore
	} from 'vuex'
	import dateTime from '@/static/js/date.js'
	const { proxy } : any = getCurrentInstance()
	const store = useStore()
	let userinfo = uni.getStorageSync('userinfo')
	let emojiShow = ref(false)//表情弹窗
	let gather : any = reactive({
		i: 0,//选中下标
		moreIndex: 0,
		article: {}, //文章列表
		articleId: null,
		isShow: false,//自己评论弹窗
		replyShow: false,//回复弹窗
		operateShow: false, //评论操作弹窗
		commentText: '',
		isFixed: false,
		commentList: [],
		currentObj: {},//当前选择的评论
		currentList: [],//当前用户评论列表
	})
	let text = ref('转发')
	let loadingShow = ref(false)

	const apiTry : Function = inject('$try')
	
	const getArticleList = async (id : string | number, cb = () => { }) => {
		const [err, res] = await apiTry(user.getArticleListId({
			id: id,
			userid: userinfo.userid,
		}))
		if (err) return
		gather.article = res.data
		if (res.data.authorid === userinfo.userid) {
			text.value = '编辑'
		}
		loadingShow.value = true
		cb()
	}
	watch(() => gather.isShow, () => {
		if (!gather.isShow) return gather.currentObj = {}; gather.commentText = ''
	})
	//编辑
	const edit = () => {
		//用户自己编辑
		if (gather.article.authorid === userinfo.userid) {
			if(gather.article.video) {
				uni.navigateTo({
					url: `/pages_home/sendVideo/index?id=${gather.article.id}&video=${gather.article.video}`,
					success: () => {
						setTimeout(() => {
							uni.$emit('update', gather.article)
						}, 100)
					}
				})
			}else{
				uni.navigateTo({
					url: `/pages_home/writeArticle/index?id=${gather.article.id}&img=${gather.article.img}`,
					success: () => {
						setTimeout(() => {
							uni.$emit('update', gather.article)
						}, 100)
					}
				})
			}
			
		} else {	//不是本人就转发
			store.commit('chatUser', gather.article)
			if(gather.article.video) {
				uni.navigateTo({
					url: `/pages_home/sendVideo/index?type=1`
				})
			}else { 
				uni.navigateTo({
					url: `/pages_home/writeArticle/index?type=1`
				})
			}
		}
	}
	//1：没有关注	0：关注了
	const onFollow = (isgz : number) => {
		if (!userinfo.userid) return uni.redirectTo({
			url: '/pages_logins/logins'
		})
		if (isgz) return followAdd()	//1
		followCancel() //0
	}
	//取消关注
	const followCancel = async () => {
		const res = await chat.followCancel({
			id: gather.article.followId,
		})
		uni.showToast({
			title: res.msg,
			icon: 'none'
		})
		gather.article.isgz = 1
		getArticleList(gather.articleId)
	}
	//关注
	const followAdd = async () => {
		const res = await chat.followAdd({
			userid: gather.article.authorid,///被关注者id不是自己
			fanid: userinfo.userid //粉丝id	关注后你就是粉丝
		})
		uni.showToast({
			title: res.msg,
			icon: 'none'
		})
		gather.article.isgz = 0
		getArticleList(gather.articleId)
	}
	//点赞
	const giveLike = async (id : number, authorid : number) => {
		if (authorid == userinfo.userid) return uni.showToast({
			title: '不能给自己点赞',
			icon: 'none'
		})
		const res = await article.giveLike({
			articleid: id,
			userid: authorid
		})
		if (res.msg === '点赞成功') {
			gather.article.isdz = 1
		} else if (res.msg === '取消成功') {
			gather.article.isdz = 0
		}
		uni.showToast({
			title: res.msg,
			icon: 'none'
		})
	}

	/* ----------------------评论操作------------------------*/
	//0点击评论文字	1点击评论数	2点击评论
	const outerLayer = (item : object, index : number) => {
		gather.currentObj = item
		gather.replyShow = true
		getCommentListId(gather.articleId, 0, gather.currentObj.id, (data) => {
			gather.currentList = data
		})
	}
	const onComment = async (type : number, item = {}, index = 0, moreIndex = 0) => {
		gather.moreIndex = moreIndex
		gather.currentObj = item
		// console.log(gather.currentObj.level)
		switch (type) {
			case 0:
				gather.isShow = true
				break
			case 2:
				gather.isShow = true
				break
		}

	}
	//评论发送
	const onConfirm = (e, type = 0) => {
		interface form {
			[propName : string] : any
		}
		let user = {
			handimg: userinfo.handimg,
			username: userinfo.username,
			reviewerid: userinfo.userid,
			content: gather.commentText,
		}
		let value = e.detail.value
		let obj : form = {
			articleid: gather.articleId,
			content: value,
			type: 0,	//0文字	1图片
		}
		if (type === 0) {
			if (gather.currentObj.id) {
				obj.replyid = gather.currentObj.reviewerid
				obj.level = 1
				obj.parent_id = gather.currentObj.id
			}
			createCommentInfo(obj, (id : number) => {
				getCommentListId(obj.articleid, 0, 0, (data : any[]) => {
					gather.currentList = data
				})
				gather.commentText = ''
				gather.isShow = false
			})

		} else if (type === 2) {	//回复
			obj.replyid = gather.currentObj.reviewerid
			obj.level = 2
			if (gather.currentObj.level === 2) {
				obj.parent_id = gather.currentList[gather.moreIndex].id
			} else {
				obj.parent_id = gather.currentObj.id
			}
			createCommentInfo(obj, (id : number) => {
				if (gather.currentObj.level === 0) {
					gather.currentList.push({
						...user,
						replyid: obj.replyid,
						level: 1,
						is_child: 0,
						id: id
					})
				} else if (gather.currentObj.level === 1) {
					if (!gather.currentList[gather.moreIndex].children) {
						gather.currentList[gather.moreIndex].children = []
					}

					gather.currentList[gather.moreIndex].children.push({
						...user,
						replyid: obj.replyid,
						level: 2,
						is_child: 1,
						id: id
					})
				} else if (gather.currentObj.level === 2) {
					if (!gather.currentList[gather.moreIndex].children) {
						gather.currentList[gather.moreIndex].children = []
					}
					gather.currentList[gather.moreIndex].children.push({
						...user,
						replyid: obj.replyid,
						level: 2,
						id: id
					})
				}

			})

			gather.commentText = ''
		}
	}
	const createCommentInfo = async (obj : object, cb : Function) => {
		const res = await article.createCommentInfo(obj)
		if (res.status === 200) {
			cb(res.data)
		}
	}
	//获取父级评论列表
	const getCommentListId = async (id : number | string, type = 0, parentid = 0, cb : Function) => {
		const res = await article.getCommentListId({
			articleid: id,
			parent_id: parentid
		})
		//如果是子级则直接return
		if (parentid) return cb(res.data)

		gather.commentList = res.data
		if (type == 1) {
			cb(res.data)
		}
	}
	//获取子级评论

	//查看更多
	const seeMore = (item, i) => {
		gather.moreIndex = i
		item.is_child = 0
		item.children = []
		getCommentListId(gather.articleId, 0, item.id, (data : any) => {
			item.children = data
		})
	}
	//删除评论
	const delCommentListId = async (id : number | string) => {
		console.log(id)
		const res = await article.delCommentListId({
			id: id
		})
		if (res.status === 200) {

		}
	}
	/* ----------------------end------------------------ */
	const fixed = () => {
		gather.isFixed = true
	}
	const unfixed = () => {
		gather.isFixed = false
	}

	const pageScrollto = () => {
		setTimeout(() => {
			uni.createSelectorQuery().select('.scroll-view').boundingClientRect((data : any) => {
				uni.createSelectorQuery().select(".main").boundingClientRect((res : any) => {
					uni.pageScrollTo({
						scrollTop: data.top - res.top,
						duration: 100
					});
				}).exec()
			}).exec();
		}, 500)
	}
	onLoad((op) => {
		gather.articleId = op.id
		getArticleList(op.id, () => {
			getCommentListId(op.id, op.type, 0, () => {
				pageScrollto()
			})

		})
	})
	const renovate = (id, parentid) => {
		getCommentListId(id, 0, parentid, (data) => {
			gather.currentList = data
		})
	}
	const filterDate = computed(() => (item : any) => {
		return dateTime.timeago(new Date(item))
	})
	const skip = (str : string) => {
		uni.navigateTo({
			url: str,
		})
	}
	const onEmoji = (item : String) => {
		gather.commentText = gather.commentText.concat(item)
	}
	//按钮事件
	const open = (i : number) : void => {
		switch (i) {
			case 1:
				break
			case 2:
				emojiShow.value = !emojiShow.value
				break
			case 3:
				
				break
		}
	}
</script>

<template>
	<page-loading mode="if" :show="loadingShow">
		<view class="main">
			<u-navbar :title="gather.article.title" height="40"></u-navbar>
			<view class="head flex">
				<view class="head-img" @click="skip(`/pages_home/personalInfo/index?id=${gather.article.authorid}`)">
					<image :src="gather.article.handimg?gather.article.handimg:'../static/img/headimg.jpg'"></image>
				</view>
				<view style="margin-left: 20rpx;" class="flex flex-dir-c flex-jc-sa">
					<view>{{gather.article.username}}</view>
					<view>{{filterDate(gather.article.pubdate)}}</view>
					<view>{{gather.article.address}}</view>
				</view>

				<view class="gz" v-if="gather.article.authorid !== userinfo.userid"
					@click="onFollow(gather.article.isgz)">
					{{gather.article.isgz?'关注':'已关注'}}
				</view>
				<view v-if="gather.article.authorid == userinfo.userid" class="reading flex flex-dir-c flex-jc-c">
					<view>阅读量</view>
					<view>{{gather.article.heat}}</view>
				</view>
			</view>

			<view class="content">
				<image v-if="gather.article.img" mode="aspectFill" :src="gather.article.img"/>
				<video v-else-if="gather.article.video" :src="gather.article.video"></video>
				<rich-text :nodes="gather.article.content"></rich-text>
			</view>
			<!-- 转发 -->
			<view v-if="gather.article.forward" class="content" style="background-color: whitesmoke;">
				<view class="description" @click="skip(`/pages_home/detail?id=${gather.article.forward.id}`)">
					<text @click.stop="skip(`/pages_home/personalInfo/index?id=${gather.article.forward.authorid}`)" style="color: rgb(237, 115, 37)">@{{gather.article.forward.username}}</text>
					<rich-text :nodes="gather.article.forward.content"></rich-text>
				</view>
				<view>
					<image v-if="gather.article.forward.img" mode="aspectFill" :src="gather.article.forward.img">
					</image>
					<video v-else-if="gather.article.forward.video" :src="gather.article.forward.video"></video>
				</view>
			</view>
			<view class="comment">
				<view class="flex flex-jc-sb comment-header">
					<view class="flex">
						<view>转发<text>10</text></view>
						<view style="margin-left: 30rpx;">评论<text>10</text></view>
					</view>
					<view>赞<text>100</text></view>
				</view>
				<u-sticky @fixed="fixed" @unfixed="unfixed">
					<scroll-view :scroll-y="gather.isFixed" class="scroll-view">
						<view v-for="(item,index) in gather.commentList" :key="index" class="flex comment-main">
							<view class="head-img">
								<image :src="item.handimg"></image>
							</view>
							<view class="comment-right f1" @click="onComment(0, item)">
								<view>{{item.username}}</view>
								<view>{{item.content}}</view>
								<view class="comment-count" @click.stop="outerLayer(item, index)" v-if="item.is_child">
									查看更多评论
									<u-icon name="arrow-right" color="rgb(68,167,255)" size="20"></u-icon>
								</view>
								<view>{{filterDate(item.createtime)}} 来自成都</view>
							</view>
						</view>
					</scroll-view>
				</u-sticky>


			</view>
			<view style="height: 40px;background-color: #fff;">
				<view class="card-list-set flex flex-jc-sa flex-ai-c">
					<view class="set-icon" @click="edit">
						<u-icon size="36rpx" name="zhuanfa" color="#000"></u-icon>
						<text>{{text}}</text>
					</view>
					<view class="set-icon" @click="onComment(2)">
						<u-icon size="36rpx" name="more-circle" color="#000"></u-icon>
						<text>评论</text>
					</view>
					<view class="set-icon" @click.stop="giveLike(gather.article.id,gather.article.authorid)">
						<u-icon size="36rpx" name="thumb-up" :color="gather.article.isdz?'red':'#000'"></u-icon>
						<text>赞</text>
					</view>
				</view>
			</view>

			<!-- 评论弹窗 -->
			<u-popup mode="bottom" v-model="gather.isShow">
				<view style="height: 500rpx;" v-if="emojiShow">
					<emoji @change="onEmoji" />
				</view>
				<view class="popup-input">
					<input :placeholder="gather.currentObj.id?`回复@${gather.currentObj.username}`:'发表你的评论'"
						@confirm="onConfirm" v-model="gather.commentText" />
				</view>
				<view class="icon flex flex-jc-sa flex-ai-c">
					<view class="pic bci"></view>
					<view class="bq bci" @click="open(2)"></view>
					<u-icon name="plus-circle" size="50"></u-icon>
				</view>
			</u-popup>
			<u-popup mode="bottom" v-model="gather.replyShow">
				<view class="comment" style="margin-top: 0;">
					<view class="flex flex-jc-sb flex-ai-c comment-header">
						<u-icon name="reload"
							@click="renovate(gather.articleId,gather.commentList[gather.i].id)"></u-icon>
						<view>{{gather.currentList.length}}条回复</view>
						<u-icon name="close" @click="gather.replyShow = false"></u-icon>
					</view>
					<scroll-view @touchmove.stop.prevent scroll-y style="height: 80vh">
						<view class="flex comment-main">
							<view class="head-img">
								<image :src="gather.commentList[gather.i].handimg"></image>
							</view>
							<view class="comment-right f1" @click="onComment(0, gather.commentList[gather.i])">
								<view>{{gather.commentList[gather.i].username}}</view>
								<view>{{gather.commentList[gather.i].content}}</view>
								<view>{{filterDate(gather.commentList[gather.i].createtime)}} 来自成都</view>
							</view>
						</view>
						<view style="height: 20rpx;background-color: rgb(230, 230, 230);"
							v-show="gather.currentList.length">
						</view>
						<view v-for="(item,index) in gather.currentList" :key="item.id" class="comment-main">
							<view class="flex">
								<view class="head-img">
									<image :src="item.handimg"></image>
								</view>
								<view class="comment-right f1" @click="onComment(0, item,0, index)">
									<view>{{item.username}}</view>
									<view>{{item.content}}</view>
									<view class="comment-more" style="color: rgb(68,167,255);"
										@click.stop="seeMore(item, index)" v-if="item.is_child">
										展开查看更多
										<u-icon name="arrow-down" color="rgb(68,167,255)" size="20"></u-icon>
									</view>
									<view>{{filterDate(item.createtime)}} 来自成都</view>
								</view>
							</view>

							<view>
								<tree :list="item.children" @onComment="onComment" :i="index" @seeMore="seeMore" />
							</view>
						</view>

					</scroll-view>
					<view class="popup-input">
						<input :placeholder="'回复@' + gather.currentObj.username" @confirm="onConfirm($event, 2)"
							v-model="gather.commentText" />
					</view>
				</view>
			</u-popup>
		</view>
	</page-loading>
</template>

<style lang="scss" scoped>
	 // 使用全局样式样式去掉
	 * { touch-action: pan-y !important; } 
	.reading{
		position: absolute;
		right: 20rpx;
		width: 130rpx;
		height: 70rpx;
		font-size: 12rpx;
		text-align: center;
		border: 1px solid rgba(0,0,0,0.2);
		color: rgba(0,0,0,0.7);
		border-radius: 40rpx;
	}
	page {
		background-color: rgb(230, 230, 230);
	}

	:deep(.uni-scroll-view) {
		overscroll-behavior-y: contain !important;
	}

	.main {
		.gz {
			text-align: center;
			width: 100rpx;
			line-height: 50rpx;
			color: rgb(247, 119, 14);
			height: 50rpx;
			border: 1px solid rgb(247, 119, 14);
			border-radius: 30rpx;
			position: absolute;
			right: 20rpx;
		}

		.head {
			background-color: #fff;
			padding: 20rpx;

			.head-right {}
		}

		.content {
			background-color: #fff;
			padding: 0 20rpx 20rpx 20rpx;

			image {
				width: 100%;
				height: 500rpx;
			}

			video {
				width: 100%;
			}

		}

		.scroll-view {

			height: calc(100vh - 80px);
		}

		// 评论
		.comment {
			background-color: #fff;
			margin-top: 20rpx;

			&-header {
				margin: 0 20rpx;
				line-height: 70rpx;
				border-bottom: 1px solid rgb(230, 230, 230);

				text {
					margin-left: 10rpx;
				}
			}

			&-count {
				font-size: 20rpx;
				color: rgb(68, 167, 255);
				background-color: rgb(245, 245, 245);
				padding: 15rpx 0 15rpx 10rpx;
			}

			&-right {
				margin-left: 20rpx;
			}

			&-main {
				padding: 20rpx;
			}
		}

		.card-list-set {
			width: 100%;
			position: fixed;
			bottom: 0;
			border-top: 1px solid rgb(200, 200, 200);
			height: 80rpx;
			background-color: #fff;

			.set-icon {
				vertical-align: middle;

				text {
					margin-left: 10rpx;
				}
			}
		}

		.popup-input {

			padding: 20rpx 20rpx;

			:deep(input) {
				height: 70rpx;
				padding: 0 20rpx !important;
				border-radius: 35rpx;
				background-color: rgb(245, 245, 245);
				font-size: 28rpx;
			}
		}

		.icon {
			margin-bottom: 20rpx;
		}
	}
</style>